//
//  DataVisitor.m
//  CToolBox
//
//  Created by SC on 16/12/13.
//  Copyright © 2016年 SC. All rights reserved.
//

#import "DataVisitor.h"
#import "LocalCacheHandler.h"
#import "INetDataCheckOperation.h"
#import "Utils.h"

NSString *const YJActionInfoPostNotification = @"YJActionInfoPostNotification";


@interface DataVisitor ()

@property (nonatomic, copy) NSString *cacheKey;
@property (nonatomic, strong) NSURLSessionDataTask *task;


@end

@implementation DataVisitor

#pragma mark - GET

- (NSString *)executeGETWithUrl:(NSString *)url
                   Params:(NSDictionary *)params
                      tag:(id)tag
             expireLength:(long)expireLength
             successBlock:(succeedBlock)success
             failureBlock:(failureBlock)failure
{
    //设置缓存的key
    _cacheKey = [self getCacheKeyWithParams:params url:url];
    if (expireLength == 0) {//不存缓存
        [self getRemoteDataWithUrl:url
                            params:params
                               tag:tag
                      expireLength:expireLength
                      successBlock:success
                      failureBlock:failure];
    }
    else{
        //取缓存
        [self getLocalDataWithKey:_cacheKey complete:^(BOOL isExpired, id object) {
            
            if (!object) {//缓存没数据，直接走网络
                [self getRemoteDataWithUrl:url
                                    params:params
                                       tag:tag
                              expireLength:expireLength
                              successBlock:success
                              failureBlock:failure];
                
            }else{//缓存有数据
                if (isExpired == YES) {//缓存过期 (不重新缓存)
                    if(success){
                        [self parse:object
                                url:url
                              cache:NO
                           cacheKey:_cacheKey
                       expireLength:expireLength
                       successBlock:success
                       failureBlock:failure];
                    }
                    
                    //推迟2秒加载网络数据 (重新缓存)
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [self getRemoteDataWithUrl:url
                                            params:params
                                               tag:tag
                                      expireLength:expireLength
                                      successBlock:success
                                      failureBlock:failure];
                    });
                    
                }else{//缓存没过期 (不重新缓存)
                    if(success){
                        [self parse:object
                                url:url
                              cache:NO
                           cacheKey:_cacheKey
                       expireLength:expireLength
                       successBlock:success
                       failureBlock:failure];
                    }
                }
            }
        }];
    }
    return _cacheKey;
}

/** 获取网络数据的方法 */
- (void)getRemoteDataWithUrl:(NSString *)url
                      params:(NSDictionary *)params
                         tag:(id)tag
                expireLength:(long)expireLength
                successBlock:(succeedBlock)success
                failureBlock:(failureBlock)failure
{
    [self getRequestWithUrl:url
                     params:params
                        tag:tag
                      cache:YES
                   cacheKey:_cacheKey
               expireLength:expireLength
               successBlock:success
               failureBlock:failure];
}

/** 获取本地数据的方法 */
- (void)getLocalDataWithKey:(NSString *)key
                   complete:(cacheCompleteBlock)cacheComplete
{
    [[LocalCacheHandler shareInstanceMethod] getValueWithKey:key complete:cacheComplete];
}

/** 存储本地数据的方法 */
- (void)setLocalDataWithKey:(NSString *)key
                     object:(NSDictionary *)object
               expireLength:(long)expireLength
{
    [[LocalCacheHandler shareInstanceMethod] saveOrUpdateWithKey:key dic:object expireLength:expireLength];
}

#pragma mark - POST

- (void)executePOSTWithUrl:(NSString *)url
                    Params:(NSDictionary *)params
                       tag:(id)tag
              successBlock:(succeedBlock)success
              failureBlock:(failureBlock)failure
{
    _task = [NetWorkManager postWithUrl:url params:params tag:tag successBlock:^(NSDictionary *dictObject) {
        
       
               
        [self actionInfoHandle:dictObject];

        [self parse:dictObject
                url:url
              cache:NO
           cacheKey:nil
       expireLength:0
       successBlock:success
       failureBlock:failure];
        
    } failureBlock:^(NSError *error) {
        DTOError *dtoError = [[DTOError alloc] init];
        dtoError.Message = error.userInfo[@"NSLocalizedDescription"];
        dtoError.ErrorCode = error.code;
        //网络请求失败，发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:DEF_NOTIFINAME_REQUESTFAILURE object:nil];
        if (failure) {
            failure(dtoError);
        }
        
    }];
    
}

#pragma mark - 取消网络请求
//单个
- (void)cancelSingleRequest
{
    [self.task cancel];
}

//全部
+ (void)cancelAllRequest
{
    [NetWorkManager cancelAll];
}

#pragma mark - 公共事件处理

- (void)actionInfoHandle:(id)respondObject{
    
    if(![respondObject isKindOfClass:[NSDictionary class]]){
        return;
    }
    NSDictionary *action = respondObject[@"Action"];
    if(action){
        [[NSNotificationCenter defaultCenter] postNotificationName:YJActionInfoPostNotification object:action];
    }
}


#pragma mark - Private

//获取网络数据(网络请求)
- (void)getRequestWithUrl:(NSString *)url
                   params:(NSDictionary *)params
                      tag:(id)tag
                    cache:(BOOL)cache
                 cacheKey:(NSString *)cacheKey
             expireLength:(long)expireLength
             successBlock:(succeedBlock)success
             failureBlock:(failureBlock)failure
{
    
    
    //网络请求
    _task = [NetWorkManager getWithUrl:url params:params tag:tag successBlock:^(NSDictionary *dictObject) {
        
        [self actionInfoHandle:dictObject];

        [self parse:dictObject
                url:url
              cache:cache
           cacheKey:cacheKey
       expireLength:expireLength
       successBlock:success
       failureBlock:failure];
        
    } failureBlock:^(NSError *error) {
        DTOError *dtoError = [[DTOError alloc] init];
        dtoError.Message = error.userInfo[@"NSLocalizedDescription"];
        dtoError.ErrorCode = error.code;
        //网络请求失败，发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:DEF_NOTIFINAME_REQUESTFAILURE object:nil];
        if (failure) {
            failure(dtoError);
        }
        
    }];
    
}

/**
 *  解析请求回来的数据 并缓存（需要的话,GET）
 *
 *  @param object   接口返回的数据
 *  @param url      请求地址（缓存用）
 *  @param cache    是否存数据库操作
 *  @param success 回调
 */
- (void)parse:(NSDictionary *)object
          url:(NSString *)url
        cache:(BOOL)cache
     cacheKey:(NSString *)cacheKey
 expireLength:(long)expireLength
 successBlock:(succeedBlock)success
 failureBlock:(failureBlock)failure
{
    [[INetDataCheckOperation shareInstanceMethod] checkObject:object successBlock:^(id respondObject) {
        
        if(success){
            success(respondObject);
            if (expireLength == 0) {
                return;
            }
            //存缓存
            if(cache){
                [self setLocalDataWithKey:cacheKey object:object expireLength:expireLength];
            }
        }

    } failureBlock:^(id respondObject) {
        if (failure) {
            failure(respondObject);
        }
    }];
    
}

//设置缓存的key
- (NSString *)getCacheKeyWithParams:(NSDictionary *)params
                                url:(NSString *)url
{
    //暂时没有用户数据，待处理
//    NSString *memberId = [CSSManager getUserOperator].userIdentityModel.MemberId;
//    NSString *key;
//    key = [NSString stringWithFormat:@"%@%@",url,memberId];
    NSString *key;
    key = [NSString stringWithFormat:@"%@",url];
    if (params != nil) {
        NSArray *keysArray = [params allKeys];
        for (int i = 0; i < keysArray.count; i++) {
            NSString *dicKey = keysArray[i];
            NSString *dicValue = params[dicKey];
            key = [NSString stringWithFormat:@"%@%@%@",key,dicKey,dicValue];
        }
    }
    return key;
}

- (void)downloadDateWithUrl:(NSString*)url
                 pathString:(NSString *)pathString
           downloadResponse:(downloadSuccessBlock)downloadResponse
   downloadProgressResponse:(downloadProgressBlock)downloadProgressResponse
{
    [NetWorkManager downloadWithManager:url pathString:pathString successBlock:^(id targetUrl) {
        downloadResponse(targetUrl);
    } progressBlock:^(CGFloat progressValue) {
        downloadProgressResponse(progressValue);
    }];
}




@end
